var app = getApp(),
  fn = app.fn;

Page({
  data: {
    skuData: [],
    num: 1,
    rec_id: '',
    skuNum: 0,
    cartNum: [],
    shopImgList: [],
    viewHeight: '',
    tabIndex: 1,
    suppId: '',
    selectIndex: 0,
    classifyIndex: 0,
    modalStatus: false,
    fmodalStauts :false,
    attrStatus: false,
    detailStatus: false,
    activeStatus: true,
    zhizhaoStatus: true,
    cartStatus: false,
    tranAnimate: '',
    scrollId: '',
    submitStr: '',
    checkCart: 0,
    currentTab: 0
  },
  // 查看其它活动
  openActive: function (e) {
    let that = this;
    let animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateY(300).step();
    this.setData({
      tranAnimate: animation.export(),
      activeStatus: false
    });
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        tranAnimate: animation.export()
      })
    }, 150);

    if (!this.data.activeStatus) {
      this.showModal();
    }
  },
  //活动消失
  closeActive: function () {
    let that = this;
    let animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateY(200).step();
    that.setData({
      tranAnimate: animation.export()
    });
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        tranAnimate: animation.export(),
        activeStatus: true
      })
    }, 150)
    this.hideModal();
  },
  //查看执照
  openZhizhao: function () {
    let that = this;
    let animation = wx.createAnimation({
      duration: 100,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateX(-500).step();
    this.setData({
      tranAnimate: animation.export(),
      zhizhaoStatus: false
    });
    setTimeout(function () {
      animation.translateX(0).step()
      that.setData({
        tranAnimate: animation.export()
      })
    }, 100);
  },
  //隐藏执照
  closeZhizhao: function () {
    let that = this;
    let animation = wx.createAnimation({
      duration: 100,
      timingFunction: 'linear'
    });
    that.animation = animation;
    animation.translateX(-500).step();
    that.setData({
      tranAnimate: animation.export()
    });
    setTimeout(function () {
      animation.translateX(0).step()
      that.setData({
        tranAnimate: animation.export(),
        zhizhaoStatus: true
      })
    }, 100)
  },
  //查看店面照片
  openShopFace: function () {
    wx.previewImage({
      urls: this.data.shopImgList
    })
  },
  //点击遮罩隐藏 
  modalClick: function () {
    if (!this.data.activeStatus) {
      this.closeActive();
      this.hideModal();
      return;
    }
  },
 

  //有规格的商品 减去
  delskuCart: function (e) {


    var that = this;
    let newindex = e.currentTarget.dataset.index;
    let itemName = e.currentTarget.dataset.id;

    let goodsListItem = "skuInfo.goods_number";

    var skuNum = --itemName.goods_number;
    if (skuNum >= 0) {

      this.setData({
        [goodsListItem]: skuNum
      })

      var rec_id = "";

      if (that.data.rec_id) {
        rec_id = that.data.rec_id;
      } else {
        rec_id = itemName.rec_id;
      }




      console.log(that.data.rec_id);

      fn.apiData({
        url: 'flow.php',
        data: {
          step: 'update_group_cart',
          user_id: app.globalData.uid,
          goods_id: that.data.goodId,
          number: skuNum,
          rec_id: rec_id
        }, success: function (res) {

          if (res.data.code == 0) {

            that.getCartNumData();
            that.getData();
            // countdown(that)
            // that.skuClose();
          }
        }
      });
      //  }
    }
  },
  //有规格的商品 加入
  addskuCart: function (e) {

    var that = this;




    let itemName = e.currentTarget.dataset.id;


    let goodsListItem = "skuInfo.goods_number";


    var skuNum = ++itemName.goods_number;


    this.setData({
      [goodsListItem]: skuNum
    })

    var submitStr = '';
    for (var i = 0; i < this.data.skuData.length; i++) {
      if (this.data.skuData[i].selected != null) {

        var selectedid = this.data.skuData[i].selected;



        if (submitStr != '') {
          submitStr += ',';
        }
        submitStr += this.data.skuData[i].values[selectedid].id;

      }
    }



    fn.apiData({
      url: 'flow.php',
      data: {
        step: 'add_to_cart',
        user_id: app.globalData.uid,
        goods_id: that.data.goodId,
        num: 1,
        spec: submitStr
      }, success: function (res) {
        // 0=>添加成功；1=>商品不存在，购物车添加失败；2=>添加失败；3=>用户和商品ID不能为空
        // wx.showToast({
        //   title: res.data.error_msg,
        //   icon: "success",
        //   duration: 2000
        // });
        console.log(JSON.stringify(res) + "添加规格");
        if (res.data.code == 0) {
          that.setData({
            rec_id: res.data.data.rec_id,

          })

          that.getCartNumData();
          that.getData();
          // countdown(that)
          // that.skuClose();
        }
      }
    });
    //  }

  },
  //无规格的商品 减去  
  delcart: function (e) {


    var that = this;
    let goodindex = e.currentTarget.dataset.index;
    let itemName = e.currentTarget.dataset.id;
    let catindex = e.currentTarget.dataset.catindex;

    var skuNum = --itemName.num;

    let goodsListItem = "productDetail[" + catindex + "].goods[" + goodindex + "].num";

    console.log(JSON.stringify(this.data.productDetail[catindex ].goods[goodindex]));
    if (skuNum >= 0) {

      this.setData({
        [goodsListItem]: skuNum
      })

      var rec_id = "";

      if (itemName.rec_id != null) {
        rec_id = itemName.rec_id;

      } else {
        rec_id = that.data.rec_id;
      }

      fn.apiData({
        url: 'flow.php',
        data: {
          step: 'update_group_cart',
          user_id: app.globalData.uid,
          goods_id: itemName.id,
          number: skuNum,
          rec_id: rec_id
        }, success: function (res) {
          // 0=>添加成功；1=>商品不存在，购物车添加失败；2=>添加失败；3=>用户和商品ID不能为空
          // wx.showToast({
          //   title: res.data.error_msg,
          //   icon: "success",
          //   duration: 2000
          // });
          if (res.data.code == 0) {

            that.getCartNumData();
          }
        }
      });
      //  }
    }
  },
  //底部 添加的商品 减去
  delallcart: function (e) {

    let itemName = e.currentTarget.dataset.id;


    var that = this;

    var skuNum = itemName.goods_number - 1;
    if (skuNum >= 0) {
      fn.apiData({
        url: 'flow.php',
        data: {
          step: 'update_group_cart',
          user_id: app.globalData.uid,
          goods_id: itemName.goods_id,
          number: skuNum,
          rec_id: itemName.rec_id
        }, success: function (res) {
          // 0=>添加成功；1=>商品不存在，购物车添加失败；2=>添加失败；3=>用户和商品ID不能为空
          // wx.showToast({
          //   title: res.data.error_msg,
          //   icon: "success",
          //   duration: 2000
          // });
          if (res.data.code == 0) {
            that.getCartNumData();
            that.getData();
          }
        }
      });
      //  }
    }
  },
  //底部 添加的商品 加入
  addallcart: function (e) {
    let itemName = e.currentTarget.dataset.id;
    var that = this;
    if (itemName.goods_attr_id == null) {

      itemName.goods_attr_id = '';
    }


    fn.apiData({
      url: 'flow.php',
      data: {
        step: 'add_to_cart',
        user_id: app.globalData.uid,
        goods_id: itemName.goods_id,
        num: 1,
        spec: itemName.goods_attr_id,
      }, success: function (res) {
        // 0=>添加成功；1=>商品不存在，购物车添加失败；2=>添加失败；3=>用户和商品ID不能为空
        // wx.showToast({
        //   title: res.data.error_msg,
        //   icon: "success",
        //   duration: 2000
        // });
        if (res.data.code == 0) {


          that.getCartNumData();
          that.getData();
          // countdown(that)
          // that.skuClose();
        }
      }
    });
    //  }

  },
  //详情页面  减去
  deldetailcart: function (e) {


    var that = this;

    let itemName = e.currentTarget.dataset.id;


    let goodsListItem = "pitemName.num";
    var skuNum = --itemName.num;

    if (skuNum >= 0) {


      let goodsListItem2 = "productDetail[" + this.data.typeindex + "].goods[" + this.data.checkGoodDetailsindex + "].num";



      this.setData({
        [goodsListItem]: skuNum,
        [goodsListItem2]: skuNum
      })

      var rec_id = "";
      if (itemName.rec_id != 0) {
        rec_id = itemName.rec_id;

      } else {

        rec_id = that.data.rec_id;
      }




      fn.apiData({
        url: 'flow.php',
        data: {
          step: 'update_group_cart',
          user_id: app.globalData.uid,
          goods_id: itemName.id,
          number: skuNum,
          rec_id: rec_id
        }, success: function (res) {
          // 0=>添加成功；1=>商品不存在，购物车添加失败；2=>添加失败；3=>用户和商品ID不能为空
          // wx.showToast({
          //   title: res.data.error_msg,
          //   icon: "success",
          //   duration: 2000
          // });
          if (res.data.code == 0) {


            that.getCartNumData();
            that.getData();
            // countdown(that)
            // that.skuClose();
          }
        }
      });
      //  }
    }
  },
  //详情页面(选规格) 
  adddeDDtailCart: function (e) {
    this.setData({
      attrStatus: true,
      detailStatus: false
    });

    this.skuOpen(e);

    this.showModal();

  },
  //详情页面  加入
  adddetailCart: function (e) {

    var that = this;

    let itemName = e.currentTarget.dataset.id;


    let goodsListItem = "pitemName.num";
    
    console.log(this.data.typeindex );
    var skuNum = ++itemName.num;
    let goodsListItem2 = "productDetail[" + this.data.typeindex + "].goods[" + this.data.checkGoodDetailsindex + "].num";

    this.setData({
      [goodsListItem]: skuNum,
      [goodsListItem2]: skuNum
    })


    fn.apiData({
      url: 'flow.php',
      data: {
        step: 'add_to_cart',
        user_id: app.globalData.uid,
        goods_id: itemName.id,
        num: 1
      }, success: function (res) {
        // 0=>添加成功；1=>商品不存在，购物车添加失败；2=>添加失败；3=>用户和商品ID不能为空
        // wx.showToast({
        //   title: res.data.error_msg,
        //   icon: "success",
        //   duration: 2000
        // });
        if (res.data.code == 0) {

          that.setData({

            'rec_id': res.data.data.rec_id,
          })
          that.getCartNumData();
          that.getData();
          // countdown(that)
          // that.skuClose();
        }
      }
    });
    //  }

  },

  //选择规格 
  skuOpen: function (e) {
    var that = this;
    let itemName = e.currentTarget.dataset.id;

    //无规格加入购物车
    if (itemName.is_attr == '0') {

      let goodindex = e.currentTarget.dataset.index;
      let carindex = e.currentTarget.dataset.catindex;
      let goodsListItem = "productDetail[" + carindex + "].goods[" + goodindex + "].num";
      let goodsrec_id = "productDetail[" + carindex + "].goods[" + goodindex + "].rec_id";
      var num = ++itemName.num;

      this.setData({
        [goodsListItem]: num
      });
      this.addCart2(itemName.id, goodsrec_id);
      return false;
    }
    //有规格 
    fn.apiData({
      url: 'flow.php',
      data: {
        act: 'get_spec',
        goods_id: itemName.id,
        user_id: app.globalData.uid,
      },
      success: function (res) {
        if (res.data.code == 0) {
          // apiFinish();

          wx.hideToast();

          for (var index in res.data.data) {

            res.data.data[index].selected = 0;

          }

          that.setData({
            'skuData': res.data.data,
            'goodId': itemName.id,
            'skuInfo': res.data.data[0].values[0]

          })
          console.log(JSON.stringify(res.data.data[0].values[0]));
          that.checkSpecCart();

        }
      }
    });

    this.setData({
      itemskuName: itemName,
      attrStatus: true
    });
    this.showModal();

  }, 
  //加入购物车
  addCart2: function (e,item) {
    var id = e;
    var that = this;

    fn.apiData({
      url: 'flow.php',
      data: {
        step: 'add_to_cart',
        user_id: app.globalData.uid,
        goods_id: that.data.uid,
        goods_id: id,
        num: 1
      }, success: function (res) {

        // wx.showToast({
        //   title: res.data.error_msg,
        //   icon: "success",
        //   duration: 2000
        // });
        if (res.data.code == 0) {
          that.getCartNumData();
          that.setData({
            [item] : res.data.data.rec_id
          })
          console.log(JSON.stringify(res) + item + "Ad");
          return;
          // that.getData();
        }  
        wx.showToast({
          title: res.msg,
        })
      }
    });
    //  }

  },
  onLoad: function (options) {


    this.getScreenWidth();
    console.log(JSON.stringify(options) + "传递的参数");
    this.data.suppId = options.id;
    var self = this;
    var t = setInterval(function () {
      if (app.globalData.uid != null) {

        self.getInitData(options);
        self.checkSetting();

        clearInterval(t);
      }
    }, 50);
    this.checkSetting();
  },
  //检测有没有user_id
  checkSetting: function () {
    var that = this;

    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          app.checkSession()
        } else {
          wx.navigateTo({
            url: '../userInfoLogin/index',
          })
        }
      }
    })
  },
  //获取商品 
  getData: function () {

    var that = this;
    fn.apiData({
      url: 'supplier.php',
      data: {
        act: 'goods',
        supplier_id: that.data.pid,
        user_id: app.globalData.uid,
        activityId: that.data.aid
      },
      success: function (res) {
        if (res.data.code == 0) {

          for (var index in res.data.data) {
            for (var index2 in res.data.data[index].goods) {



              res.data.data[index].goods[index2].num = res.data.data[index].goods[index2].cgoods_num;
            }

          }




          that.setData({
            'productDetail': res.data.data
            //'productDetail.description': srcArr,
            //'sku.choosePirce': res.data.result.ladderPrice
          });


        }
      }
    });
  },
  //分享
  onShareAppMessage: function () {

    var that = this;
    return {
      title: that.data.banner.shop_name,
      desc: that.data.banner.shop_title,
      imageUrl: that.data.banner.logo,
    }
  },
  //获取初始化数据 
  getInitData: function (options, callback) {
    var that = this,
      flag = 0;

    that.setData({
      pid: options.id,//商家id

    });
    //获取头部数据
    fn.apiData({
      url: 'supplier.php',
      data: {
        act: 'header',
        supplier_id: that.data.pid
      },
      success: function (res) {
        if (res.data.code == 0) {
          apiFinish();
          that.setData({ 'banner': res.data.data });
          res.data.data.shop_img.forEach(function (item, index) {
            that.data.shopImgList.push(item.url);
          })
          //店面照片
          that.data.shopImgList.push(res.data.data.shop_face);

          wx.setNavigationBarTitle({
            title: res.data.data.shop_name
          })
        }
      }
    });

    //获取商品数据
    fn.apiData({
      url: 'supplier.php',
      data: {
        act: 'goods',
        supplier_id: that.data.pid,
        user_id: app.globalData.uid,
        activityId: that.data.aid
      },
      success: function (res) {
        if (res.data.code == 0) {
          apiFinish();

          for (var index in res.data.data) {
            for (var index2 in res.data.data[index].goods) {

              res.data.data[index].goods[index2].num = res.data.data[index].goods[index2].cgoods_num;
            }
          }

          that.setData({
            'productDetail': res.data.data
            //'productDetail.description': srcArr,
            //'sku.choosePirce': res.data.result.ladderPrice
          });
        }
      }
    });


    function apiFinish(callBack) {
      ++flag;
      if (flag >= 5) {
        wx.hideToast();
        if (!!callBack) callBack();
      }
    }

    that.getCartNumData();
  },
  //添加的购物车数据 
  getCartNumData: function () {
    var that = this;

    fn.apiData({
      url: 'flow.php',
      data: {
        act: 'get_cart',
        user_id: app.globalData.uid,
        supplier_id: that.data.pid,
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.hideToast();

          that.setData({
            cartNum: res.data.data,
          })


        }
      }
    });
  },
  //获取屏幕大小
  getScreenWidth: function () {
    const that = this;
    wx.getSystemInfo({
      success: function (res) {
        let clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR;
        that.setData({
          viewHeight: calc
        })
      },
    })
  },
  //Tab 切换
  changTab: function (e) {
    this.setData({
      tabIndex: e.target.dataset.id
    });
  },
  //滚动到某个位置
  scrollTo: function (e) {
    let target = e.currentTarget.dataset.id;

    let index = e.currentTarget.dataset.index;

    this.setData({
      scrollId: target,
      classifyIndex: index
    })
  },
  


  //清空购物车
  clearCart: function () {
    var that = this;
    fn.apiData({
      url: 'flow.php',
      data: {
        step: 'clear',
        supplier_id: that.data.pid,
        user_id: app.globalData.uid,
      },
      success: function (res) {
        if (res.data.code == 0) {


          that.checkcartClose();


        }
      }
    });

  },

  //关闭购物车
  closeCartWin: function (e) {
    this.hideModal();
    this.setData({
      attrStatus: false
    });
  },
  //查看详情页
  checkGoodDetails: function (e) {
    let idss = e.currentTarget.dataset.type;
    let id = e.currentTarget.dataset.id;
    
    this.setData({
      pitemName: id,
      checkGoodDetailsindex: e.currentTarget.dataset.index,
      typeindex: e.currentTarget.dataset.index,
      detailStatus: true
    });
    this.showModal();
  },
  //关闭详情页
  closeDetailWin: function (e) {
    this.setData({
      detailStatus: false
    })

    // this.getData();
    this.hideModal();
  },



  checkSpecCart: function () {


    var submitStr = '';
    for (var i = 0; i < this.data.skuData.length; i++) {
      if (this.data.skuData[i].selected != null) {

        var selectedid = this.data.skuData[i].selected;



        if (submitStr != '') {
          submitStr += ',';
        }
        submitStr += this.data.skuData[i].values[selectedid].id;

      }
    }
    var that = this;
    fn.apiData({
      url: 'flow.php',
      data: {
        act: 'get_spec_cart',
        spec: submitStr,
        user_id: app.globalData.uid,
      },
      success: function (res) {
        if (res.data.code == 0) {
          // apiFinish();
          that.setData({
            rec_id : res.data.data.rec_id,
            'skuInfo.goods_number' : res.data.data.goods_number
          });
          // that.setData({

          //   skuInfo: res.data.data,

          // });
          console.log(JSON.stringify(res) + "获取规格数量 Id");
          wx.hideToast();

          // that.setData({
          //   'skuData': res.data.data,
          //   'goodId': itemName.id,
          //   'skuInfo': res.data.data[0].values[0]
          //   //   itemskuName: itemName,
          //   //   attrStatus: true
          // })

          // this.showModal();

        } else {
          wx.hideToast();



        }
      }
    });

  },
  //提交订单检测
  bindCheckout: function () {

    var that = this;
    var difference = that.data.cartNum.difference;
    if (that.data.cartNum.count == 0) {

      wx.showToast({
        title: '请先买必点品',
        icon: 'none',
        duration: 2000
      })
      return false;


    }

    if (difference != 0) {

      wx.showToast({
        title: ' 不满足商家的最低起送',
        icon: 'none',
        duration: 2000
      })

      return false;

    }


    fn.apiData({
      url: 'flow.php',
      data: {
        act: 'pre_checkout',
        supplier_id: that.data.pid,
        user_id: app.globalData.uid,
      },
      success: function (res) { 
        if (res.data.code != 0) {

          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          //滚动到某个位置
          let target = 'goods_'+res.data.data.goods_id;
          that.setData({
            scrollId: target
          })
          return;
        } else {
          wx.navigateTo({
            url: '../firmOrder/firmOrder?id=' + that.data.pid
          })

          wx.hideToast();
        }
      }
    });


  },
  //选择规格
  selectAttr: function (e) {

    let goodsAttrItem = "skuData[" + e.target.dataset.type + "].selected";

    // console.log(JSON.stringify(e));
    this.setData({
      [goodsAttrItem]: e.target.dataset.index,
      skuInfo: e.target.dataset.id
    });


    this.checkSpecCart();


    this.showModal();
  },
  //添加的商品 关闭
  checkcartClose: function (e) {
    let that = this;
    this.setData({
      cartStatus: (!that.data.cartStatus)
    });
    that.getCartNumData();
    if (this.data.cartStatus) {
      this.showModal('footer');
    } else {
      this.getData();
      this.hideModal('footer');
    }
  },
  //遮罩显示
  showModal: function () {
    if(arguments[0] == 'footer'){
      this.setData({
        fmodalStauts : true
      })
      return;
    } 
    this.setData({
      modalStatus: true
    });
  },
  //遮罩隐藏
  hideModal: function () {
    if (arguments[0] == 'footer') {
      this.setData({
        fmodalStauts: false
      })
      return;
    } 
    this.setData({
      modalStatus: false
    });
  },
  
  //下拉刷新
  onPullDownRefresh() {
    this.getInitData({ "id": this.data.suppId }, function () {
      wx.stopPullDownRefresh();
    });
  },

})
